﻿using HuaweiCloud.SDK.Cdn.V1;
using HuaweiCloud.SDK.Cdn.V1.Model;
using HuaweiCloud.SDK.Core;
using HuaweiCloud.SDK.Core.Auth;
using HWCDNLogAnalysis.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HWCDNLogAnalysis
{
    public partial class frmDownLog : Form
    {
        //获取Configuration对象
        System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
        string ak = "", sk = "", cropid = "";
        public frmDownLog()
        {
            InitializeComponent();
        }

        private void frmDownLog_Load(object sender, EventArgs e)
        {
            this.ak = config.AppSettings.Settings["HWCloud:AK"].Value;
            this.sk = config.AppSettings.Settings["HWCloud:SK"].Value;
            this.cropid = config.AppSettings.Settings["HWCloud:CropId"].Value;
            txtDomain.Text= config.AppSettings.Settings["HWCloud:Domain"].Value;
            dtDay.Value = DateTime.Now.AddDays(-1);
            txtFolder.Text=AppDomain.CurrentDomain.BaseDirectory+"logs";
            if (!Directory.Exists(txtFolder.Text))
            {
                Directory.CreateDirectory(txtFolder.Text);
            }
        }

        private void lnkSetting_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var frm = new frmHWCDNSetting();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                //重新加载配置
                config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                this.ak = config.AppSettings.Settings["HWCloud:AK"].Value;
                this.sk = config.AppSettings.Settings["HWCloud:SK"].Value;
                this.cropid = config.AppSettings.Settings["HWCloud:CropId"].Value;
            }
        }

        private void btnFolder_Click(object sender, EventArgs e)
        {
            var folder = new FolderBrowserDialog();
            folder.Description = "日志文件保存路径";
            folder.SelectedPath =AppDomain.CurrentDomain.BaseDirectory;

            if (folder.ShowDialog() == DialogResult.OK)
            {
                txtFolder.Text = folder.SelectedPath;
            }
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            if(ak == null || sk == null || txtDomain.Text == "")
            {
                MessageBox.Show("AK/SK 域名不能空");
                return;
            }
            var _d = DateTime.Parse(dtDay.Text);
            if(_d < DateTime.Now.AddDays(-30) || _d > DateTime.Now.AddDays(1))
            {
                MessageBox.Show("请选择30天内某一天");
                return;
            }
            var dic=new Dictionary<string, string>();
            dic["HWCloud:Domain"] = txtDomain.Text;
            FunUtils.AddConfig(dic, true);
            setText("日志获取...");
            btnGet.Enabled = false;
            //logDown();
            Thread thread = new Thread(new ThreadStart(logDown));

            thread.Start();
        }
        private long DateTimeToTimestamp(DateTime datetime)
        {
            DateTime dd = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            DateTime timeUTC = DateTime.SpecifyKind(datetime, DateTimeKind.Utc);//本地时间转成UTC时间
            TimeSpan ts = (timeUTC - dd);
            return (Int64)ts.TotalMilliseconds;//精确到毫秒
        }
        private void setText(string msg)
        {
            BeginInvoke(new Action(() => {
                if (msg == "suc")
                {
                    btnGet.Enabled = true;
                }
                else
                {
                    txtLog.Text=txtLog.Text.Insert(0, msg + "\r\n");
                }
            }));
         
        }
        private void logDown()
        {
            var config = HttpConfig.GetDefaultConfig();
            config.IgnoreSslVerification = true;
            var auth = new GlobalCredentials(ak, sk);

            var client = CdnClient.NewBuilder()
                    .WithCredential(auth)
                    .WithRegion(CdnRegion.ValueOf("cn-north-1"))
                    .WithHttpConfig(config)
                    .Build();
            var _day = DateTimeToTimestamp(DateTime.Parse(dtDay.Text).Date);
            
            var req = new ShowLogsRequest
            {
                DomainName =txtDomain.Text,
                //PageNumber=10000,
                //EnterpriseProjectId=string.IsNullOrEmpty(cropid)?"0":cropid,
                QueryDate = _day
            };
            setText($"域名：{txtDomain.Text},日期：{dtDay.Text}");
            try
            {
                var resp = client.ShowLogs(req);
                if(resp != null && resp.HttpStatusCode == 200&&resp.Total>0)
                {
                    setText($"获取到日志文件：{resp.Total}个，开始下载文件");
                    var _logs=resp.Logs;
                    var _lst=new List<CDNLog>();
                    foreach(var log in _logs)
                    {
                        var _m = new CDNLog()
                        {
                            Name = log.Name,
                            DomainName = log.DomainName,
                            Link = log.Link,
                            Size = log.Size.GetValueOrDefault(0)
                        };
                        _lst.Add(_m);
                    }
                    var _f = FileUtils.FileDown(txtFolder.Text, _lst);
                    setText($"下载成功，合并日志文件：{_f}");
                    setText("suc");
                }
                else
                {
                    setText("暂无日志文件");
                    setText("suc");
                }
               
                //var respStatusCode = resp.HttpStatusCode;
                //Console.WriteLine(respStatusCode);
                
            }
            catch (RequestTimeoutException requestTimeoutException)
            {
                setText(requestTimeoutException.ErrorMessage);
                //Console.WriteLine(requestTimeoutException.ErrorMessage);
            }
            catch (ServiceResponseException clientRequestException)
            {
                setText(clientRequestException.ErrorMsg);
                //Console.WriteLine(clientRequestException.HttpStatusCode);
                //Console.WriteLine(clientRequestException.ErrorCode);
                //Console.WriteLine(clientRequestException.ErrorMsg);
            }
            catch (ConnectionException connectionException)
            {
                setText(connectionException.ErrorMessage);
                //Console.WriteLine(connectionException.ErrorMessage);
            }
        }
    }
}
